package cn.com.anysdk.sms.exception;

import cn.com.anysdk.sms.monitor.SmsMonitorManager;
import cn.com.anysdk.sms.monitor.SmsOperationContext;
import lombok.extern.slf4j.Slf4j;

/**
 * SMS异常处理器
 */
@Slf4j
public class SmsExceptionHandler {
    private static final SmsExceptionHandler INSTANCE = new SmsExceptionHandler();
    private final SmsMonitorManager monitorManager = SmsMonitorManager.getInstance();

    private SmsExceptionHandler() {}

    public static SmsExceptionHandler getInstance() {
        return INSTANCE;
    }

    /**
     * 处理异常
     */
    public void handleException(Throwable ex, SmsOperationContext context) {
        SmsException smsException = convertToSmsException(ex);
        monitorManager.handleException(smsException, context);
        log.error("SMS operation failed: {}", context, ex);
    }

    /**
     * 将异常转换为SmsException
     */
    private SmsException convertToSmsException(Throwable ex) {
        if (ex instanceof SmsException) {
            return (SmsException) ex;
        }

        // 网络相关异常
        if (ex instanceof java.net.SocketTimeoutException) {
            return new SmsException("SMS operation timeout", ex);
        }
        if (ex instanceof java.net.ConnectException) {
            return new SmsException("Failed to connect to SMS provider", ex);
        }

        // 其他异常
        return new SmsException("Internal SMS service error", ex);
    }

    /**
     * 创建业务异常
     */
    public SmsException createBusinessException(String message) {
        return new SmsException(message);
    }
}
